<template>
	<view class="comment-page" :style="isPc?'padding: 4px 12px;':'padding: 2px 6px;'">
		<!-- 顶部标题 -->
		<view class="page-header">
			<uv-icon class="icon" name="arrow-leftward" size="20" @click="$emit('revert')"></uv-icon>
			<text class="title">用户评论</text>
			<text class="count">({{ total }}条)</text>
		</view>
		<!-- 评论输入框 -->
		<view class="comment-input-box">
			<image :src="vuex_user.portrait" class="user-avatar"></image>
			<input v-model="newComment" class="input" placeholder="说点什么吧..." placeholder-class="placeholder"
				maxlength="200" :focus="autoFocus" @focus="onInputFocus" />
			<button class="submit-btn" :class="{ disabled: !canSubmit }" :disabled="!canSubmit" @click="submitComment">
				发送
			</button>
		</view>
		<!-- 评论列表 -->
		<scroll-view class="comment-list" scroll-y :scroll-top="commentScrollTop" @scroll="handleScroll"
			@scrolltolower="loadMore">
			<view v-if="comments[0]" v-for="comment in comments" :key="comment._id" class="comment-item">
				<image :src="comment.portrait" class="avatar"></image>
				<view class="content-box">
					<view class="header">
						<text>{{ comment.nickname }}</text>
						<text>{{ $uv.timeFormat(comment.createdAt) }}</text>
					</view>
					<text class="content">{{ comment.content }}</text>
					<!-- 评论操作 -->
					<view v-if="vuex_user" class="action-bar">
						<view class="action-btn" @click="toggleLike(comment)">
							<uni-icons :type="comment.likeStatus ? 'heart-filled' : 'heart'" size="18"
								:color="comment.likeStatus ? '#f56c6c' : '#999'"></uni-icons>
							<text class="action-text" :style="{ color: comment.likeStatus ? '#f56c6c' : '#999' }">
								{{ comment.likes || '赞' }}
							</text>
						</view>
						<view class="action-btn" @click="showReplyInput(comment)">
							<uni-icons type="chat" size="18" color="#999"></uni-icons>
							<text class="action-text">回复</text>
						</view>
						<view v-if="comment.userId === vuex_user._id" class="action-btn"
							@click="deleteComment(comment)">
							<uni-icons type="trash" size="18" color="#999"></uni-icons>
							<text class="action-text">删除</text>
						</view>
					</view>

					<!-- 回复列表 -->
					<view v-if="comment.children && comment.children.length" class="reply-list">
						<view v-for="reply in comment.children" :key="reply._id" class="reply-item">
							<image :src="reply.portrait" class="avatar"></image>
							<view class="reply-content">
								<view class="reply-header">
									<text class="nickname">{{ reply.nickname }}</text>
									<text v-if="reply.ancestorId"> 回复 @{{ comment.nickname }}</text>
								</view>
								<text class="content">{{ reply.content }}</text>
								<!-- 评论操作 -->
								<view class="action-bar_r">
									<view style="display: flex;justify-content: flex-start;">
										<view class="action-btn" @click="toggleLike(reply)">
											<uni-icons :type="reply.likeStatus ? 'heart-filled' : 'heart'" size="16"
												:color="reply.likeStatus ? '#f56c6c' : '#999'"></uni-icons>
											<text class="action-text" v-if="isPc"
												:style="{ color: reply.likeStatus ? '#f56c6c' : '#999' }">
												{{ reply.likes || '赞' }}
											</text>
										</view>
										<view class="action-btn" @click="showReplyInput(comment,reply)">
											<uni-icons type="chat" size="16" color="#999"></uni-icons>
											<text class="action-text" v-if="isPc">回复</text>
										</view>
										<view v-if="reply.userId === vuex_user._id" class="action-btn"
											@click="deleteComment(reply)">
											<uni-icons type="trash" size="16" color="#999"></uni-icons>
											<text class="action-text" v-if="isPc">删除</text>
										</view>
									</view>

									<text>{{ $uv.timeFormat(reply.time) }}</text>
								</view>
							</view>
						</view>
					</view>

					<!-- 回复输入框 && (!repliesId || repliesId === replies._id)-->
					<view v-if="activeReplyId === comment._id" class="reply-input-box">
						<input v-model="replyContent" class="input"
							:placeholder="`回复${replies?replies.nickname:comment.nickname}...`"
							placeholder-class="placeholder" maxlength="200" :focus="true"
							@confirm="submitReply(repliesId?replies:comment)" />
						<button class="submit-btn" :class="{ disabled: !canSubmitReply }" :disabled="!canSubmitReply"
							@click="submitReply(repliesId?replies:comment)">
							发送
						</button>
					</view>
				</view>
			</view>

			<!-- 加载状态 -->
			<view v-if="loading" class="loading-more">
				<uni-load-more status="loading"></uni-load-more>
			</view>
			<view v-else-if="!hasMore" class="no-more">
				<text>没有更多评论了</text>
			</view>
		</scroll-view>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script>
	import {
		getName,
		commentName,
		deleteName,
		like
	} from '@/common/api.js';
	export default {
		props: {
			taskid: {
				type: [Array, String],
				default: ''
			},
			userInfo: Object,
			autoFocus: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				comments: [], // 当前显示的评论列表
				replies: {},
				newComment: '', // 新评论内容
				replyContent: '', // 回复内容
				total: 0, // 总评论数
				page: 1, // 当前页码
				pageSize: 10, // 每页数量
				hasMore: true, // 是否有更多
				loading: false, // 加载状态
				activeReplyId: null, // 当前激活的回复框
				repliesId: null, // 当前激活的回复框
				commentScrollTop: 0, // 滚动位置
				targetPosition: 0, // 目标滚动位置
				isScrolling: false, // 防止重复触发
				// autoFocus: false, // 自动聚焦
			};
		},
		watch: {
			total(newVal, oldVal) {
				this.$emit('total', newVal);
			},
		},
		computed: {
			canSubmit() {
				return this.$uv.trim(this.newComment).length >= 2;
			},
			canSubmitReply() {
				return this.$uv.trim(this.replyContent).length >= 2;
			},
		},
		mounted() {
			this.loadComments();
		},
		methods: {
			// 滚动到指定位置（核心方法）
			scrollToPosition(position) {
				// 1. 重置为0触发视图更新
				this.scrollTop = 0

				// 2. 使用$nextTick确保DOM更新完成
				this.$nextTick(() => {
					// 3. 添加微小延迟确保平台兼容
					setTimeout(() => {
						this.targetPosition = position
						this.scrollTop = position
					}, 50)
				})
			},

			// 滚动事件记录（可选）
			handleScroll(e) {
				if (!this.isScrolling) {
					this.targetPosition = e.detail.scrollTop
				}
			},

			// 示例：滚动到顶部
			scrollToTop() {
				this.scrollToPosition(0)
			},

			// 示例：滚动到底部
			scrollToBottom() {
				// 需要实际计算内容高度
				const scrollHeight = 5000 // 替换为实际内容高度
				this.scrollToPosition(scrollHeight)
			},
			// // 滚动事件处理（可选）
			// handleScroll(e) {
			// 	// 记录实际滚动位置
			// 	console.log(e?.detail?.scrollTop);
			// },
			// 加载评论
			async loadComments() {
				if (this.loading || !this.hasMore) return;

				this.loading = true;
				uni.showLoading({
					title: '加载中',
					mask: true
				});

				try {
					const res = await getName('comment', {
						custom: {
							auth: true,
							toast: false,
							catch: true,
						},
						params: {
							id: this.taskid,
							page: this.page,
							pageSize: this.pageSize
						}
					});
					const newComments = res.list
						.filter(c => c && typeof c === 'object' && c._id != null)
					// .map(c => ({
					// 	...c,
					// 	likeStatus: false
					// }));
					if (this.page === 1) {
						this.comments = newComments;
					} else {
						this.comments = [...this.comments, ...newComments];
					}

					this.total = res.total;
					this.hasMore = this.comments.length < res.total;
					this.page++;

				} catch (e) {
					uni.showToast({
						title: e.msg || '加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					uni.hideLoading();
				}
			},

			// 加载更多
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.loadComments();
				}
			},

			// 提交评论
			async submitComment() {
				if (!this.canSubmit) return;

				uni.showLoading({
					title: '提交中',
					mask: true
				});

				try {
					const res = await commentName('add', {
						content: this.newComment,
						flowId: this.taskid,
					}, {
						custom: {
							auth: true,
							catch: false,
						}
					})
					// 在列表顶部添加新评论
					const newComment = {
						...res,
						likeStatus: false,
						children: []
					};
					this.comments.unshift(newComment);
					this.total++;
					this.newComment = null;

					// 滚动到顶部
					this.commentScrollTop = 0;
					this.$nextTick(() => {
						setTimeout(() => {
							this.commentScrollTop = 0
						}, 50)
					})

					uni.showToast({
						title: '评论成功'
					});

				} catch (e) {
					uni.showToast({
						title: e.message,
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 显示回复框
			showReplyInput(comment, replies = null) {
				this.activeReplyId = comment._id;
				this.replyContent = '';
				if (replies) {
					this.repliesId = replies._id;
					this.replies = replies;
				} else {
					this.repliesId = null;
					this.replies = null;
				}
				// 滚动到对应位置
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select(`#comment-${comment._id}`).boundingClientRect();
					query.exec(res => {
						if (res[0]) {
							uni.pageScrollTo({
								scrollTop: res[0].top - 50,
								duration: 300
							});
						}
					});
				});
			},

			// 提交回复
			async submitReply(comment) {
				if (!this.canSubmitReply) return;

				uni.showLoading({
					title: '提交中',
					mask: true
				});

				try {
					const res = await commentName(`reply`, {
						content: this.replyContent,
						parentId: comment._id,
						flowId: this.taskid,
						ancestorId: comment.ancestorId || comment.parentId
					}, {
						custom: {
							auth: true,
							catch: false,
						}
					})
					console.log(res, this.comments, comment._id);
					// 添加到对应评论的回复列表
					let targetComment = this.comments && comment && this.comments.find(c => c._id == comment._id);
					if (targetComment) {
						targetComment.children.push(res);
					}

					this.activeReplyId = null;
					this.replyContent = '';

					uni.showToast({
						title: '回复成功'
					});

				} catch (e) {
					uni.showToast({
						title: e.message,
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 点赞/取消点赞
			async toggleLike(comment) {
				try {
					// 先更新UI状态
					comment.likeStatus = !comment.likeStatus;
					comment.likes = comment.likeStatus ? comment.likes + 1 : Math.max(0, comment.likes - 1);

					// 发送请求到后端
					await like({
						id: comment._id
					}, {
						custom: {
							auth: true,
							toast: true
						}
					})
				} catch (e) {
					// 失败则回退状态
					comment.likeStatus = !comment.likeStatus;
					comment.likes = comment.likeStatus ? comment.likes + 1 : Math.max(0, comment.likes - 1);

					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				}
			},

			// 删除评论
			deleteComment(comment) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这条评论吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const res = await deleteName(`comment/${comment._id}`, {}, {
									custom: {
										auth: true,
										catch: false,
									}
								})
								// 2. 更新本地评论数据，从列表中移除
								this.comments = this.filterComments(this.comments, comment._id);

								this.total--;

								uni.showToast({
									title: '删除成功'
								});

							} catch (e) {
								uni.showToast({
									title: e.msg || '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			// 过滤目标评论及其所有子评论
			filterComments(comments, targetId, or = false) {
				return comments
					.filter(comment => comment._id !== targetId) // 过滤掉目标评论
					.map(comment => {
						// 递归过滤子评论
						if (comment.children && comment.children.length) {
							return {
								...comment,
								children: this.filterComments(comment.children, targetId)
							};
						}
						return comment;
					});
			},
			// 输入框聚焦时滚动到底部
			onInputFocus() {
				// uni.pageScrollTo({
				// 	scrollTop: 10000,
				// 	duration: 300
				// });
			}
		}
	};
</script>

<style lang="scss" scoped>
	.comment-page {
		// background-color: #f5f7fa;
		box-sizing: border-box;
		height: auto;
		width: auto;

		.page-header {
			display: flex;
			align-items: center;

			.icon {
				margin-right: 10px;
				cursor: pointer;
			}

			.icon:hover {
				font-weight: bold;
			}


			.title {
				font-size: 15px;
				font-weight: bold;
				color: #333;
			}

			.count {
				margin-left: 7px;
				font-size: 12px;
				color: #999;
			}
		}

		.comment-input-box {
			// position: absolute;
			display: flex;
			align-items: center;
			background-color: #ffffff;
			border: 1px solid #eee;
			border-radius: 8px;
			padding: 5px;
			margin: 3px 0px;
			box-shadow: 0 4px 6px rgba(0, 0, 0, 0.04);

			.user-avatar {
				width: 35px;
				height: 35px;
				border-radius: 50%;
				margin-right: 10px;
				background-color: #eee;
			}

			.input {
				flex: 1;
				height: 35px;
				padding: 0 10px;
				font-size: 14px;
				background: #f8f8f8;
				border-radius: 6px;
			}

			.submit-btn {
				width: 55px;
				height: 30px;
				line-height: 30px;
				margin-left: 10px;
				background: #007aff;
				color: white;
				font-size: 13px;
				border-radius: 6px;
				transition: all 0.3s;

				&.disabled {
					background: #cccccc;
					opacity: 0.7;
				}
			}
		}

		.comment-list {
			height: calc(100vh - 380px);
			// min-height: 100%;

			.comment-item {
				display: flex;
				padding-top: 5px;
				margin-bottom: 5px;
				border-radius: 8px;

				.avatar {
					width: 35px;
					height: 35px;
					border-radius: 50%;
					margin-right: 8px;
					background-color: #eee;
				}

				.content-box {
					flex: 1;
				}

				.header {
					display: flex;
					justify-content: space-between;
					font-size: 12px;
					color: #999;
				}

				.content {
					font-size: 14px;
					line-height: 1.5;
					color: #444;
				}

				.action-bar {
					display: flex;
					font-size: 12px;
					color: #999;

					.action-btn {
						display: flex;
						align-items: center;
						margin-right: 30rpx;
						color: #999;

						.action-text {
							margin-left: 4px;
							font-size: 13px;
						}
					}
				}

				.action-bar_r {
					display: flex;
					justify-content: space-between;
					font-size: 12px;
					color: #999;

					.action-btn {
						display: flex;
						align-items: center;
						margin-right: 30rpx;
						color: #999;

						.action-text {
							margin-left: 4px;
							font-size: 13px;
						}
					}
				}

				.reply-list {
					// background: #f9f9f9;

					.reply-item {
						display: flex;
						padding-top: 7px;

						.reply-content {
							flex: 1;
						}

						.reply-header {
							display: flex;
							justify-content: flex-start;
							font-size: 12px;
						}

						.nickname {
							color: #999;
						}


						.avatar {
							width: 30px;
							height: 30px;
							border-radius: 50%;
							margin-right: 5px;
							background-color: #eee;
						}
					}
				}

				.reply-input-box {
					display: flex;
					align-items: center;
					margin-top: 5px;
					boder: 1px solid #ccc;

					.input {
						flex: 1;
						height: 30px;
						padding: 0 10px;
						font-size: 13px;
						background: #f8f8f8;
						border-radius: 4px;
					}

					.submit-btn {
						height: 30px;
						margin-left: 10px;
						background: #007aff;
						color: white;
						border-radius: 6px;
						transition: all 0.3s;
						width: 55px;
						height: 30px;
						line-height: 30px;
						font-size: 13px;

						&.disabled {
							background: #cccccc;
							opacity: 0.7;
						}
					}
				}
			}

			.loading-more,
			.no-more {
				text-align: center;
				padding: 10px;
				color: #999;
				font-size: 13px;
			}
		}
	}
</style>